package java_test.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectonTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
//        Person p1 = new Person("Tom", 12);
//        p1.age = 10;
//        System.out.println(p1);
//        p1.show();
        //reflectonTest1();
        reflectonTest2();

    }

    public static void reflectonTest1() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class clazz = Person.class;
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Object tom = constructor.newInstance("Tom", 12);
        Person p = (Person) tom;
        System.out.println(p);
        Field age = clazz.getDeclaredField("age");
        age.set(p, 10);
        System.out.println(p);
        Method show = clazz.getDeclaredMethod("show");
        show.invoke(p);
        System.out.println("**********************************");
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);
        Person p1 = (Person) declaredConstructor.newInstance("Jerry");
        System.out.println(p1);
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(p1, "胡宇婷");
        System.out.println(p1);
        Method showNation = clazz.getDeclaredMethod("showNation", String.class);
        showNation.setAccessible(true);
        String nation = (String) showNation.invoke(p1, "中国");
        System.out.println(nation);
    }

    public static void reflectonTest2() throws ClassNotFoundException {
        Class<Person> personClass = Person.class;
        System.out.println(personClass);
        Person p1 = new Person();
        Class<? extends Person> aClass = p1.getClass();
        System.out.println(aClass);

        Class<?> aClass1 = Class.forName("java_test.reflection.Person");
        System.out.println(aClass1);

        ClassLoader classLoader = ReflectonTest.class.getClassLoader();
        Class<?> aClass2 = classLoader.loadClass("java_test.reflection.Person");
        System.out.println(aClass2);
        System.out.println(personClass == aClass2);
    }
}
